package com.hcm.kernel.sql;

import com.hcm.kernel.util.StringUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 作用：将一个bean转化为sql的where条件，所有的属性以and连接
 * @author zhangzunwei
 */
public class Bean2SQL {

    @SuppressWarnings("rawtypes")
    public static SQLWhere getWhere(Object t, boolean... isContains) {
        SQLWhere sw = new SQLWhere();
        Class clazz = t.getClass();
        Field[] fs = clazz.getDeclaredFields();
        for (Field f : fs) {
            String name = f.getName();
            String getMethod = StringUtil.getGetMethodName(name);
            try {
                @SuppressWarnings("unchecked")
                Method method = clazz.getDeclaredMethod(getMethod);
                Object obj = method.invoke(t);

                String type = f.getType().getSimpleName();
                if (type.equalsIgnoreCase("int") || type.equalsIgnoreCase("Integer")
                        || type.equalsIgnoreCase("long") || type.equalsIgnoreCase("Long")) {
                    if (isContains != null && isContains[0]) {
                        set(sw, name, obj);
                    }
                    continue;
                } else {
                    set(sw, name, obj);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sw;
    }

    private static void set(SQLWhere sw, String key, Object obj) {
        if (obj != null && !obj.toString().equals("")) {
            sw.setWhere(key + "=:" + key);
            sw.put(key, obj);
        }
    }
}
